#include <stdlib.h>
#include "direction.h"

Coord direction_apply (Coord from, Direction dir, int steps)
{
	switch (dir) {
		default:
		case DIR_NONE:      break;
		case DIR_DOWN:      from.y += steps; break;
		case DIR_UP:        from.y -= steps; break;
		case DIR_LEFT:      from.x -= steps; break;
		case DIR_RIGHT:     from.x += steps; break;
		case DIR_LEVELDOWN: from.z -= steps; break;
		case DIR_LEVELUP:   from.z += steps; break;
	}
	
	return from;
}

/**
 * Returns the direction that a character on the [from] coordinates
 * would most likely move in to reach the [to] coordinates.
 */
Direction direction_primary (Coord from, Coord to)
{
	if ((from.z != to.z) && (from.x == to.x) && (from.y == to.y)) {
		if (from.z < to.z) return DIR_LEVELUP;
		else               return DIR_LEVELDOWN;
	} else {
		int xdiff = to.x - from.x;
		int ydiff = to.y - from.y;
		if ((xdiff == 0) && (ydiff == 0)) {
			return DIR_NONE;
		} else
		if ( abs(xdiff) < abs(ydiff) ) {
			if (ydiff < 0) return DIR_UP;
			else           return DIR_DOWN;
		} else {
			if (xdiff < 0) return DIR_LEFT;
			else           return DIR_RIGHT;
		}
	}
}

/**
 * Returns the direction that a character on the [from] coordinates
 * would move in to reach the [to] coordinates. If there are 2 options,
 * this function always prefers the option that is not given by 
 * direction_primary.
 */
Direction direction_secondary (Coord from, Coord to)
{
	if ((from.z != to.z) && (from.x == to.x) && (from.y == to.y)) {
		if (from.z < to.z) return DIR_LEVELUP;
		else               return DIR_LEVELDOWN;
	} else {
		int xdiff = to.x - from.x;
		int ydiff = to.y - from.y;
		if ((xdiff == 0) && (ydiff == 0)) {
			return DIR_NONE;
		} else
		if ( abs(xdiff) >= abs(ydiff) ) {
			if (ydiff < 0) return DIR_UP;
			else           return DIR_DOWN;
		} else {
			if (xdiff < 0) return DIR_LEFT;
			else           return DIR_RIGHT;
		}
	}
}
